﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

namespace ARPGPhotonServer.Tools
{
    /// <summary>
    /// 用于处理http请求
    /// </summary>
    public class Http
    {
        private string host;
        private List<Pair> parameters;

        public static Http Url(string host)
        {
            return new Http(host);
        }

        private Http(string host)
        {
            this.host = host;
            parameters = new List<Pair>();
        }

        public Http parameter(string key, string value)
        {
            parameters.Add(new Pair(key, value));
            return this;
        }

        /// <summary>
        /// 生成Url
        /// </summary>
        /// <returns></returns>
        private string FullUrl()
        {
            var result = new StringBuilder();
            result.Append(host);

            var ie = parameters.GetEnumerator();
            if (ie.MoveNext())
            {
                result.Append('?');
                result.Append(ie.Current);

                while (ie.MoveNext())
                {
                    result.Append('&');
                    result.Append(ie.Current);
                }
            }
            return result.ToString();
        }

        /// <summary>
        /// 发出请求,得到响应
        /// </summary>
        /// <returns>响应结果</returns>
        public bool IsLoginIn()
        {
            var request = WebRequest.Create(FullUrl());
            var response = request.GetResponse();
            var resStream = response.GetResponseStream();
            var sr = new StreamReader(resStream);
            return Convert.ToBoolean(sr.ReadToEnd());
        }

        /// <summary>
        /// 参数对
        /// </summary>
        internal class Pair
        {
            public string K { get; private set; }
            public string V { get; private set; }

            public Pair(string k, string v)
            {
                K = k ?? "";
                V = v ?? "";
            }

            public override string ToString()
            {
                try
                {
                    return K + "=" + V;
                }
                catch (Exception e)
                {
                    throw;
                }
            }
        }
    }
}